package other.xsy.passlys;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.data.model.CustomerName__c;
import com.rkhd.platform.sdk.data.model.CustomerRelevance__c;
import com.rkhd.platform.sdk.data.model.TeamMember;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import other.xsy.passlys.util.HCXObjectService;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 计划作业: 定时读取客户报备数据去除客户团队成员
 * @Author 黎炎松
 * 2024-06-14 14:32
 */
public class CustomerRelevanceSchedule implements ScheduleJob, FutureTask {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    protected XoqlService xoqlService = XoqlService.instance();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "定时读取客户报备数据去除客户团队成员 ==> ";

    // 执行定时任务
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        logger.debug(LOGGER_MSG + " 执行定时任务开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            logger.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    // 执行异步函数
    @Override
    public void execute(String s) throws ScriptBusinessException {
        batchDealCustomerRelevance();
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        new CustomerRelevanceSchedule().batchDealCustomerRelevance();
    }

    /**
     * 批量处理 客户报备数据
     */
    public void batchDealCustomerRelevance() {
        try {
            // 读取需要处理的客户报备数据  1.业务类型： 客户转移/共享 2.团队成员是否移除：否 3.客户所有人同意操作方式为：商机报备 4.审批通过 5.报备通过时间 >= 3 天
            long timestamp = System.currentTimeMillis();
            long daysTamp = 1000 * 60 * 60 * 24; // 天
            String sql = "select id,name,ownerId,customItem11__c,customerName__c,passageTime__c, (" + timestamp + " - passageTime__c) / " + daysTamp +  " as day from customerRelevance__c " +
                    "where entityType = 3330970387913381 and (teamMember__c = 2 or teamMember__c is null) and operationTypeB__c = 3 and passageTime__c is not null " +
                    " and (" + timestamp + " - passageTime__c) / "+ daysTamp +" >= 3";
            QueryResult<JSONObject> query = xoqlService.query(sql);
            List<JSONObject> records = query.getRecords();
            logger.info(LOGGER_MSG + "records = " + records);
            if (records.size() <= 0) {
                logger.info(LOGGER_MSG + "暂无需要处理的数据");
                return;
            }

            // 通过客户名称信息获取关联客户
            String customerNameIds = records.stream().map(v -> v.getString("customerName__c")).collect(Collectors.joining(","));
            sql = "select id,associatedCustomer__c from customerName__c where id in (" + customerNameIds + ")";
            QueryResult<JSONObject> accountQuery = xoqlService.query(sql);
            List<JSONObject> accountRecords = accountQuery.getRecords();
            if (accountRecords.size() <= 0) {
                logger.error(LOGGER_MSG + "批量获取关联客户信息异常");
                return;
            }

            // 获取需要删除的团队成员
            List<TeamMember> delTeamMembers = new ArrayList<>();
            List<CustomerRelevance__c> upCustomerRelevance = new ArrayList<>();
            for (JSONObject record : records) {
                // 根据客户名称找到对应的客户
                JSONObject customerName = accountRecords.stream().filter(v -> Objects.equals(v.getString("id"), record.getString("customerName__c"))).findFirst().orElse(null);
                logger.error(LOGGER_MSG + "customerName = " + customerName);
                if (customerName == null) {
                    logger.error(LOGGER_MSG + "获取关联客户信息异常");
                    continue;
                }

                // 移除客户的团队成员 （客户报备里面的 申请人、提交人）
                Long accountId = customerName.getLong("associatedCustomer__c");

                // 合并用户id
                String submitId = record.getString("customItem11__c"); // 提交人
                String ownerId = record.getString("ownerId"); // 申请人
                String userIds = Arrays.asList(submitId, ownerId).stream().distinct().collect(Collectors.joining(","));

                // 只删除普通成员 memberAttr 1：负责人  2：普通成员
                sql = "select id,memberAttr from teamMember where memberAttr = 2 and recordFrom = 1 and recordFrom_data = " + accountId + " and userId in (" + userIds + ")";
                List<TeamMember> TeamMemberList = hcxObjectService.query(sql, TeamMember.class);
                logger.error(LOGGER_MSG + "TeamMemberList = " + TeamMemberList);
                delTeamMembers.addAll(TeamMemberList);

                // 处理的数据打上标识
                CustomerRelevance__c customerRelevance__c = new CustomerRelevance__c();
                customerRelevance__c.setId(record.getLong("id"));
                customerRelevance__c.setTeamMember__c(1);
                upCustomerRelevance.add(customerRelevance__c);
            }

            logger.error(LOGGER_MSG + "delTeamMembers = " + delTeamMembers);
            if (delTeamMembers.size() > 0) {
                Boolean batchDelete = hcxObjectService.batchDelete(delTeamMembers);
                if (!batchDelete) {
                    logger.error(LOGGER_MSG + "批量删除团队成员异常");
                    return;
                }
            }

            // 对已处理的数据打上标识
            logger.error(LOGGER_MSG + "upCustomerRelevance = " + upCustomerRelevance);
            Boolean update = hcxObjectService.batchUpdate(upCustomerRelevance);
            if (!update) {
                logger.error(LOGGER_MSG + "批量修改客户报备处理标识异常");
                return;
            }

            logger.error(LOGGER_MSG + "处理成功");

        } catch (ApiEntityServiceException e) {
            logger.info(LOGGER_MSG + "处理异常:" + e.getMessage());
        }
    }



}
